<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司" prop="company">
        <el-input
          v-model="queryParams.company"
          placeholder="请输入公司"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片" prop="img">
        <el-input
          v-model="queryParams.img"
          placeholder="请输入图片"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['portal:banner:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['portal:banner:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['portal:banner:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['portal:banner:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="公司" align="center" prop="company" />
      <el-table-column label="图片" align="center" prop="img">
        <template #default="scope">
          <el-image
            style="width: 190px;display: block;"
            :src="scope.row.img[0]"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="proIndex" />
      <!-- <el-table-column label="类型" align="center" prop="type" /> -->
      <el-table-column label="是否启用" align="center" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['portal:banner:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['portal:banner:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轮播图对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body destroy-on-close >
      <el-form ref="bannerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公司" prop="company">
          <el-input v-model="form.company" placeholder="请输入公司" />
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <!-- <el-input v-model="form.img" placeholder="请输入图片" /> -->
          <el-upload ref="uploadRef"
            :http-request="customUploadRequest"
            list-type="picture-card"
            :show-file-list="showFileList"
            :auto-upload="true"
            :limit="1"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip text-red">建议尺寸357*130像素，且不超过500kb</div>
            </template>
          </el-upload>
          
        </el-form-item>
        <el-form-item label="排序" prop="proIndex">
          <el-input v-model="form.proIndex" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%" />
          </el-dialog>
  </div>
</template>

<script setup name="Banner">
import { ElLoading } from 'element-plus'
import { listBanner, getBanner, delBanner, addBanner, updateBanner, upload, deleteImg } from "@/api/portal/banner"

const { proxy } = getCurrentInstance()
const showFileList = ref(false)
const bannerList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const imgFileList = ref([])
const uploadRef = ref(null)
const bannerDialog = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    company: null,
    img: null,
    proIndex: null,
    type: null,
    status: null,
  },
  rules: {
    img: [{ required: true, message: "图片不能为空", trigger: "blur" }]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 启用轮播图
const handleStatusChange = (row) => {
  let text = row.status === 1 ? "启用" : "停用"
  proxy.$modal.confirm('确认要"' + text + '""' + row.id + '"轮播图吗？').then(function () {
    const { id, status } = row
    return updateBanner({id, status});
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
  }).catch(function () {
    row.status = row.status === 1 ? 0 : 1
  })
}

// 上传
const customUploadRequest = (option) => {
  const loadingInstance = ElLoading.service({
    text:'上传中...'
  })
  showFileList.value = false
  let formData = new FormData()
  formData.append('file', option.file)
  upload(formData).then(response => {
    // 只保留最新上传的图片
    imgFileList.value = [{ url: response.fileUrl, uid: option.file.uid }]
    // 通知 el-upload 上传成功
    option.onSuccess(response, option.file)
    showFileList.value = true
    loadingInstance.close()
  }).catch(() => {
    option.onError()
    loadingInstance.close()
  })
}

const handleUploadSuccess = (response, file, fileList) => {
  // 这里可以不做处理，imgFileList 已在 customUploadRequest 里处理
}

// 预览图片
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 删除图片
const handleRemove = (file) => {
  const currentUrl = imgFileList.value.filter(item => item.uid === file.uid)
  deleteImg({'url': currentUrl[0].url}).then(response => {
    imgFileList.value = imgFileList.value.filter(item => item.uid !== file.uid)
    // 给提示
    proxy.$modal.msgSuccess('删除成功')
  })
}

/** 查询轮播图列表 */
function getList() {
  loading.value = true
  listBanner(queryParams.value).then(response => {
    let responseList = response.rows.map(item => {
      // 将切割之后的图片以字符串的形式返回
      item.img = item.img ? item.img.split(',') : []
      return item
    })

    bannerList.value = responseList
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
  uploadRef.value.clearFiles()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    company: null,
    img: null,
    proIndex: null,
    type: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("bannerRef")
}

/** 搜索按钮操作 */
  function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加轮播图"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getBanner(_id).then(response => {
    // 只保留第一张图片
    const imgs = response.data.img ? response.data.img.split(',') : []
    form.value = response.data
    imgFileList.value = imgs.length ? [{ url: imgs[0], uid: 0 }] : []
    open.value = true
    title.value = "修改轮播图"
  })
}

/** 提交按钮 */
function submitForm() {
  if (imgFileList.value.length > 0) {
    Object.assign(form.value, { img: imgFileList.value[0].url })
  }
  proxy.$refs["bannerRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBanner(form.value).then(response => {
          uploadRef.value.clearFiles()
          imgFileList.value = []
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          
          getList()
        })
      } else {
        addBanner(form.value).then(response => {
          uploadRef.value.clearFiles()
          imgFileList.value = []
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除轮播图编号为"' + _ids + '"的数据项？').then(function() {
    return delBanner(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('portal/banner/export', {
    ...queryParams.value
  }, `banner_${new Date().getTime()}.xlsx`)
}

getList()
</script>
